package com.wisemoresystem.seal.base.plugin.login;

import java.util.Enumeration;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.ne.framework.data.util.ChkTools;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.wisemoresystem.seal.base.action.ProjBaseAction;
import com.wisemoresystem.seal.util.json.JsonTools;

/**
 * 搜索拦截器
 * 
 * @author Administrator
 * 
 */
public class SrhInterceptor implements HandlerInterceptor {

	@Override
	public void afterCompletion(HttpServletRequest req,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
	}

	@Override
	public void postHandle(HttpServletRequest req, HttpServletResponse resp,
			Object arg2, ModelAndView mv) throws Exception {

		if (arg2.getClass() == HandlerMethod.class) {
			HandlerMethod hm = (HandlerMethod) arg2;
			ProjBaseAction baseAction = (ProjBaseAction) hm.getBean();

			// 注入 json 到页面中/或者 redirect 到 下一个 action
			String srh_params = JsonTools.toJson(baseAction.getSrh_params());
			if (mv!=null && ChkTools.isNotNull(srh_params) && !"{}".equals(srh_params)) {
				mv.addObject("srh_params", srh_params);
			}

		}// #if

	}

	@Override
	public boolean preHandle(HttpServletRequest req, HttpServletResponse resp,
			Object arg2) throws Exception {
		if (arg2.getClass() == HandlerMethod.class) {
			HandlerMethod hm = (HandlerMethod) arg2;
			ProjBaseAction baseAction = (ProjBaseAction) hm.getBean();
			// 旧的参数设置进去
			String srh_params_json = req.getParameter("srh_params");
			if (ChkTools.isNotNull(srh_params_json)) {
				Map<String, Object> srh_params = JsonTools
						.jsonStrToMap(srh_params_json);
				baseAction.setSrh_params(srh_params);
			}

			// 重置新的参数
			Enumeration<String> params = req.getParameterNames();
			while (params.hasMoreElements()) {
				String param = params.nextElement();
				if (param.startsWith("srh_") && !param.equals("srh_params")) {
					baseAction.putParam(param, req.getParameter(param));
				}
			}// #while

			// 设置 分页 页码
			String pageNo = req.getParameter("pageNo");
			if (ChkTools.isNotNull(pageNo)) {
				// 页面传过来的
				int pageNum = baseAction.page.getPageNum();
				baseAction.putParam("srh_page_num", pageNum + "");
			} else {
				int srh_page_num = ChkTools.getInteger((String) baseAction
						.getSrh_params().get("srh_page_num"));
				if (srh_page_num > 1) {
					baseAction.page.setPageNum(srh_page_num);
				}
			}

		}// #if

		return true;
	}
}
